<?php

namespace collections\compare;

class ComparableObject implements Comparable
{
    /** @var mixed */
    private $val;

    /** @var callable */
    private $cmpFn;

    public function __construct($val) {
        $this->val = $val;
        if (is_numeric($val)) {
            $this->cmpFn = function($a, $b) {
                return $a - $b;
            };
        } else if (is_string($val)) {
            $this->cmpFn = function($a, $b) {
                return strcmp($a, $b);
            };
        } else {
            $this->cmpFn = function($a, $b) {
                return strcmp(serialize($a), serialize($b));
            };
        }
    }

    public function getVal() {
        return $this->val;
    }

    public function compareTo($o) {
        if ($o instanceof ComparableObject) {
            $b = $o->getVal();
        } else {
            $b = $o;
        }
        $a = $this->val;
        return call_user_func($this->cmpFn, $a, $b);
    }
}